<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="file">
    <script>
        function ajax(opa) {
            let { type, url, success, data = {}, xhr } = opa
            if (xhr) {
                xhr = xhr()
                console.log("使用人家创建好的")
            } else {
                let xhr = new XMLHttpRequest()
                console.log('自己new')
            }
            let usp = new URLSearchParams(data)
            let query = usp.toString()
            xhr.onload = function () {
                let sre = JSON.parse(xhr.responseText)
                success(sre)
            }
            if (type === 'get') {
                xhr.open(type, url + '?' + query)
                xhr.send()
            } else {
                xhr.open(type, url)
                if (data instanceof FormData) {
                    xhr.send(data)
                } else {
                    xhr.send(query)
                }
            }
        }
        let input = document.querySelector('input')
        input.onchange = function () {
            let file = this.files[0]
            let fd = new FormData()
            fd.append('file_data', file)
            ajax({
                url: 'http://127.0.0.1:3001/uploadFile',
                type: 'post',
                data: fd,
                xhr() {
                    let tempXhr = new XMLHttpRequest()
                    tempXhr.upload.onprogress = function (event) {
                        let { loaded, total } = event
                        let ser = parseInt((loaded / total) * 100) + '%'
                        console.log(ser)
                    }
                    return tempXhr
                },
                success(arr) {
                    console.log(arr);
                }
            })
            //提交普通data的数据
            // ajax({
            //     url: "http://127.0.0.1:3001/addHero",
            //     type: "post",
            //     data: {
            //         name: "444",
            //         gender: "444",
            //         img: "444"
            //     },
            //     success(result) {
            //         console.log(result);
            //     }
            // })
        }
    </script>
    <!-- <script>
          let input = document.querySelector('input')
        input.onchange = function () {
            let file = this.files[0]
            let fd = new FormData()
            fd.append('file_data', file)
            console.log(fd)
            let xhr = new XMLHttpRequest()
            xhr.open('post', 'http://127.0.0.1:3001/uploadFile')
            xhr.onload = function () {
                console.log(xhr.responseText);
            }
            xhr.send(fd)
        }
    </script> -->
</body>

</html>